<template>
  <div class="home-container" v-loading="loading">
    <!-- 下拉刷新提示 -->
    <div class="pull-refresh" :class="{ 'refreshing': isRefreshing }">
      <el-icon class="refresh-icon" :class="{ 'rotating': isRefreshing }">
        <Refresh />
      </el-icon>
      <span>{{ refreshText }}</span>
    </div>

    <!-- 顶部用户信息和搜索栏 -->
    <div class="header">
      <div class="user-info">
        <el-avatar :size="50"
          :src="userStore.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c67266epng.png'" />
        <div class="welcome-text">
          <p class="greeting">{{ getGreeting() }}</p>
          <p class="username">{{ userStore.username || '用户' }}</p>
        </div>
      </div>
      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="搜索皮肤问题/护理知识" prefix-icon="Search" @focus="showSearchHistory = true"
          @blur="handleSearchBlur">
          <template #suffix>
            <el-icon class="voice-search" @click="startVoiceSearch">
              <Microphone />
            </el-icon>
          </template>
        </el-input>
        <!-- 搜索历史 -->
        <div class="search-history" v-show="showSearchHistory && searchHistory.length > 0">
          <div class="history-header">
            <span>搜索历史</span>
            <el-icon @click="clearSearchHistory">
              <Delete />
            </el-icon>
          </div>
          <div class="history-list">
            <div v-for="(item, index) in searchHistory" :key="index" class="history-item"
              @click="handleHistoryClick(item)">
              <el-icon>
                <Timer />
              </el-icon>
              <span>{{ item }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 皮肤状况/今日推荐 -->
    <el-carousel :interval="4000" height="180px" class="recommendation-carousel">
      <el-carousel-item v-for="(item, index) in recommendations" :key="index">
        <div class="recommendation-card" :style="{ background: item.gradient }">
          <h3>{{ item.title }}</h3>
          <p>{{ item.content }}</p>
          <el-button type="primary" size="small" @click="viewRecommendationDetail(item)">
            查看详情
          </el-button>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 功能模块导航 -->
    <draggable v-model="featureList" item-key="id" class="feature-grid" @end="handleDragEnd">
      <template #item="{ element }">
        <div class="feature-item" @click="goToPage(element.path)">
          <el-icon>
            <component :is="element.icon" />
          </el-icon>
          <span>{{ element.name }}</span>
          <el-icon v-if="element.isPinned" class="pin-icon" @click.stop="togglePin(element)">
            <Star />
          </el-icon>
        </div>
      </template>
    </draggable>

    <!-- 皮肤资讯 -->
    <div class="content-section">
      <div class="section-header">
        <h3>皮肤资讯</h3>
        <el-button text type="primary" @click="loadMoreArticles">
          查看更多
        </el-button>
      </div>
      <div v-infinite-scroll="loadMoreArticles" infinite-scroll-disabled="loading" infinite-scroll-distance="10">
        <el-card v-for="(article, index) in articles" :key="index" shadow="hover" class="article-card"
          :class="{ 'fade-in': article.isNew }">
          <template #header>
            <div class="article-header">
              <span>{{ article.title }}</span>
              <el-tag size="small" :type="article.tagType">{{ article.tag }}</el-tag>
            </div>
          </template>
          <div class="article-content">
            <p>{{ article.content }}</p>
            <div class="article-footer">
              <span class="article-time">{{ article.time }}</span>
              <span class="article-views">
                <el-icon>
                  <View />
                </el-icon>
                {{ article.views }}
              </span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 加载更多提示 -->
    <div class="load-more" v-if="hasMore">
      <el-icon class="loading-icon" v-if="loading">
        <Loading />
      </el-icon>
      <span>{{ loading ? '加载中...' : '上拉加载更多' }}</span>
    </div>
  </div>
</template>

<script setup>
import {
  Delete,
  Loading,
  Microphone,
  Refresh,
  Star,
  Timer,
  View
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import draggable from 'vuedraggable'
import { useUserStore } from '../store/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const isRefreshing = ref(false)
const refreshText = ref('下拉刷新')
const searchQuery = ref('')
const showSearchHistory = ref(false)
const hasMore = ref(true)

// 搜索历史
const searchHistory = ref(['痤疮护理', '敏感肌修复', '防晒知识'])

// 推荐内容
const recommendations = ref([
  {
    title: '今日皮肤护理建议',
    content: '根据您的皮肤状况，建议使用温和的洁面产品，注意防晒，保持充足睡眠。',
    gradient: 'linear-gradient(135deg, #a8e6cf 0%, #dcedc1 100%)'
  },
  {
    title: '季节性皮肤护理',
    content: '春季注意防敏，夏季注重防晒，秋季补水保湿，冬季滋润修复。',
    gradient: 'linear-gradient(135deg, #ffd3a5 0%, #fd6585 100%)'
  },
  {
    title: '皮肤问题解决方案',
    content: '针对常见皮肤问题，提供专业的护理建议和治疗方案。',
    gradient: 'linear-gradient(135deg, #a0fe65 0%, #fa016d 100%)'
  }
])

// 功能模块列表
const defaultFeatureList = [
  { id: 1, name: '在线问诊', path: '/inquiry', icon: 'ChatDotRound', isPinned: true },
  { id: 2, name: '健康检测', path: '/healthcheck', icon: 'Monitor', isPinned: false },
  { id: 3, name: '慢病管理', path: '/chronic', icon: 'Bell', isPinned: true },
  { id: 4, name: '膳食管理', path: '/diet', icon: 'Bowl', isPinned: false },
  { id: 5, name: '体质辨识', path: '/tcmConstitution', icon: 'FirstAidKit', isPinned: false },
  { id: 6, name: '运动管理', path: '/exercise', icon: 'Timer', isPinned: false },
  { id: 7, name: '中医百科', path: '/tcmEncyclopedia', icon: 'Reading', isPinned: false },
  { id: 8, name: '健康讲堂', path: '/lecture', icon: 'School', isPinned: false },
  { id: 9, name: '个人档案', path: '/profile', icon: 'User', isPinned: false }
]

const featureList = ref(defaultFeatureList)

// 文章列表
const articles = ref([
  {
    title: '敏感肌护理指南',
    content: '温和清洁，避免刺激，选择适合的护肤品，建立健康的皮肤屏障。',
    tag: '护理',
    tagType: 'success',
    time: '2024-03-20',
    views: 1234,
    isNew: true
  },
  {
    title: '痤疮治疗新进展',
    content: '了解痤疮成因，科学用药，合理护肤，预防复发。',
    tag: '治疗',
    tagType: 'warning',
    time: '2024-03-19',
    views: 856,
    isNew: true
  }
])

// 获取问候语
const getGreeting = () => {
  const hour = new Date().getHours()
  if (hour < 12) return '上午好'
  if (hour < 18) return '下午好'
  return '晚上好'
}

// 页面跳转
const goToPage = (path) => {
  router.push(path)
}

// 处理搜索历史点击
const handleHistoryClick = (item) => {
  searchQuery.value = item
  showSearchHistory.value = false
  // 执行搜索
}

// 清除搜索历史
const clearSearchHistory = () => {
  searchHistory.value = []
  ElMessage.success('搜索历史已清除')
}

// 处理搜索框失焦
const handleSearchBlur = () => {
  setTimeout(() => {
    showSearchHistory.value = false
  }, 200)
}

// 开始语音搜索
const startVoiceSearch = () => {
  ElMessage.info('语音搜索功能开发中...')
}

// 查看推荐详情
const viewRecommendationDetail = (item) => {
  ElMessage.info(`查看${item.title}详情`)
}

// 处理拖拽结束
const handleDragEnd = () => {
  // 保存新的排序到本地存储
  localStorage.setItem('featureList', JSON.stringify(featureList.value))
}

// 切换置顶状态
const togglePin = (feature) => {
  feature.isPinned = !feature.isPinned
  // 保存置顶状态到本地存储
  localStorage.setItem('featureList', JSON.stringify(featureList.value))
}

// 加载更多文章
const loadMoreArticles = async () => {
  if (loading.value) return
  loading.value = true

  try {
    // 模拟加载更多数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    const newArticles = [
      {
        title: '春季皮肤护理指南',
        content: '春季皮肤护理重在保湿，注意调节情绪，保持心情舒畅。',
        tag: '护理',
        tagType: 'primary',
        time: '2024-03-18',
        views: 567,
        isNew: true
      }
    ]
    articles.value.push(...newArticles)
    hasMore.value = articles.value.length < 10 // 模拟数据加载完毕
  } catch (error) {
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  // 从本地存储加载功能模块排序
  const savedFeatureList = localStorage.getItem('featureList')
  if (savedFeatureList) {
    featureList.value = JSON.parse(savedFeatureList)
  } else {
    // 如果本地存储中没有数据，使用默认列表并保存到本地存储
    localStorage.setItem('featureList', JSON.stringify(defaultFeatureList))
  }
})
</script>

<style scoped>
.home-container {
  padding: 15px;
  background-color: #f7f8fa;
  min-height: calc(100vh - 50px);
  padding-bottom: 70px;
  position: relative;
}

.pull-refresh {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: translateY(-100%);
  transition: transform 0.3s;
  background-color: #fff;
}

.pull-refresh.refreshing {
  transform: translateY(0);
}

.refresh-icon {
  margin-right: 8px;
  transition: transform 0.3s;
}

.refresh-icon.rotating {
  transform: rotate(360deg);
}

.header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.welcome-text {
  margin-left: 10px;
}

.welcome-text .greeting {
  font-size: 14px;
  color: #666;
}

.welcome-text .username {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.search-bar {
  flex: 1;
  position: relative;
}

.search-history {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin-top: 5px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.voice-search {
  cursor: pointer;
  color: #409EFF;
}

.recommendation-carousel {
  margin-bottom: 20px;
}

.recommendation-card {
  height: 100%;
  padding: 20px;
  border-radius: 12px;
  color: #333;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.recommendation-card h3 {
  margin-top: 0;
  font-size: 20px;
  color: #2e8b57;
}

.recommendation-card p {
  font-size: 14px;
  margin-bottom: 15px;
  line-height: 1.5;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
  width: 100%;
}

.feature-item {
  background-color: #fff;
  padding: 15px;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
  position: relative;
}

.feature-item:active {
  transform: scale(0.98);
}

.feature-item .el-icon {
  font-size: 32px;
  color: #2e8b57;
  margin-bottom: 8px;
}

.feature-item span {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.pin-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 16px;
  color: #ff9800;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.article-card {
  margin-bottom: 15px;
  border-radius: 10px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.article-card:hover {
  transform: translateY(-2px);
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.article-views {
  display: flex;
  align-items: center;
}

.article-views .el-icon {
  margin-right: 4px;
}

.load-more {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.fade-in {
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>